using System;
using System.Linq;
using king.Db;
using king.models;
using Microsoft.EntityFrameworkCore;

namespace king.Repository
{
    public class EfRepository<T> : IRepository<T>where T: Entity
    {
        private readonly DemoDb db;

        private readonly DbSet<T> table; 

        public EfRepository()
        {
            db=new DemoDb();
            table=db.Set<T>();
        }
        public IQueryable<T> Table 
        {
            get
            {
                return table as IQueryable<T>;

            }
        }

        public void Delete(int id)
        {
            var entity=table.Where(x => x.Id == id).FirstOrDefault();

            if(entity==null)
            {
                throw new System.Exception();
            }
            table.Remove(entity);
            db.SaveChanges();
            
        }

        public T Getbyid(int id)
        {
            var entity=table.Where(x=> x.Id ==x.Id).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
                                if (entity == null)
            {
                throw new System.Exception();
            }
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreateTime = DateTime.Now;
            entity.UpdatedTime = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.Creator = 0;
         table.Add(entity);
         db.SaveChanges();
        }

        public void Update(T entity)
        {
            if(entity==null)
            {
                throw new System.Exception();

            }
            if(entity.Id==0)
            {
                throw new System.Exception();

            }
            table.Update(entity);
            db.SaveChanges();
            
        }
    }
}